package com.zjitc;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import java.io.IOException;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/4/28 14:05
 * @description:
 */
public class RabbitMQ {

  private Connection con;
  private Channel channel;
  private static final String QUEUE_NAME = "queue_register_demo";

  public RabbitMQ() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("47.94.111.174");
    factory.setPort(5672);
    factory.setVirtualHost("/");
    factory.setUsername("guest");
    factory.setPassword("guest");

    try {
      this.con = factory.newConnection();
      this.channel = this.con.createChannel();
      Consumer consumer = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope,
            BasicProperties properties,
            byte[] body) throws IOException {
          System.out.println(new String(body));
        }
      };
      this.channel.basicConsume(QUEUE_NAME, true, consumer);
    } catch (Exception ex) {
      throw new ExceptionInInitializerError("初始化rabbit消息队列连接失败\n" + ex.getMessage());
    }
  }
}
